package com.insigma.business.qrcode.common.service.impl;

import com.insigma.business.qrcode.common.service.SequenceGenerator;
import com.insigma.business.qrcode.common.service.SequenceManager;
import com.insigma.business.qrcode.common.util.DateUtils;
import com.insigma.business.qrcode.common.vo.SeqConstraintPositionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SequenceGeneratorImpl implements SequenceGenerator {
    private static final Logger logger = LoggerFactory.getLogger(SequenceGeneratorImpl.class);
    public static final String SEQUENCE_PREFIX = "seq_";
    private static final String EMPTY_HOLDER = "0";
    @Resource
    private SequenceManager sequenceManager;

    public SequenceGeneratorImpl() {
    }

    @Override
    public String nextValue(String tableName) {
        String sequenceName = this.getSequenceName(tableName);
        String nextValue = this.sequenceManager.getNextValue(sequenceName, "0");
        logger.info(String.format("序列|%s当前值为|%s", sequenceName, nextValue));
        return nextValue;
    }
    @Override
    public String genKey(String tableName) {
        String dateYMD = DateUtils.format(this.sequenceManager.getNowDate());
        String nextSeqValue = this.nextValue(tableName);
        return dateYMD + nextSeqValue;
    }
    @Override
    public String genKey(String tableName, String attachKey, SeqConstraintPositionEnum seqConstraintPositionEnum) {
        String dateYMD = DateUtils.format(this.sequenceManager.getNowDate());
        String nextSeqValue = this.nextValue(tableName);
        if (SeqConstraintPositionEnum.PREFIX == seqConstraintPositionEnum) {
            return attachKey + dateYMD + nextSeqValue;
        } else {
            return SeqConstraintPositionEnum.MIDDLE == seqConstraintPositionEnum ? dateYMD + attachKey + nextSeqValue : dateYMD + nextSeqValue + attachKey;
        }
    }

    private String getSequenceName(String tableName) {
        return "seq_" + tableName;
    }
}
